#!/user/bin/env python
# -*- coding:utf-8 -*-
# author : 洛月
# mailer  : 2870093961@qq.com
# created: 2023-04-02 23:02
# updated: 2023-04-02 23:02

from pathlib import Path
from typing import Union
import hashlib
import os
import pathlib


def get_hash_by_bytes(data: bytes) -> str:
    m = hashlib.md5()
    m.update(data)
    return m.hexdigest()


def get_hash_by_path(path: Union[str, Path]) -> str:
    with open(path, "rb") as fp:
        m = hashlib.md5()
        m.update(fp.read())
        return m.hexdigest()


def save_file_by_bytes(data: bytes, path: Path, name: Union[str, None] = None, suffix: Union[str, None] = None) -> str:
    """
    保存文件
    :param data: bytes
    :param path: 文件路径
    :param name: 文件名
    :param suffix: 文件后缀
    :return: 文件路径
    """
    filename = get_hash_by_bytes(data) if name is None else name
    if suffix is not None:
        filename += f".{suffix}"
    filepath = path / filename
    with open(filepath, "wb") as fp:
        fp.write(data)

    return str(filepath)


def mkdir(path: Union[str, Path]) -> Path:
    if isinstance(path, pathlib.WindowsPath):
        if not path.exists():
            os.makedirs(path)
            return path
    elif isinstance(path, str):
        folder = Path(path)
        if not folder.exists():
            os.makedirs(folder)
            return folder


def rmdir(path: Union[str, Path]) -> None:
    """删除目录"""
    if isinstance(path, str):
        path = Path(path)
    for item in path.iterdir():
        if item.is_file():
            item.unlink()
        else:
            rmdir(item)
    path.rmdir()


def iter_file(path: Union[Path, str]):
    with open(path, mode="rb") as file_like:
        yield from file_like
